package com.tree.backend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.OrderQueryDTO;
import com.tree.backend.entity.vo.OrderListVO;
import com.tree.backend.entity.vo.OrderVO;
import com.tree.backend.service.IDemandOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import com.tree.backend.utils.UserContext;

/**
 * 订单控制器
 * @author tree
 */
@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {
    
    private final IDemandOrderService demandOrderService;
    
    /**
     * 获取订单列表
     * @param queryDTO 查询参数
     * @return 订单分页列表
     */
    @GetMapping
    public Result<IPage<OrderListVO>> getOrderList(OrderQueryDTO queryDTO) {
        // 从当前用户获取企业ID
        Long enterpriseId = UserContext.getCurrentUserEnterpriseId();
        queryDTO.setEnterpriseId(enterpriseId);
        
        IPage<OrderListVO> orderList = demandOrderService.getOrderList(queryDTO);
        return Result.success(orderList);
    }
    
    /**
     * 获取订单详情
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("/{orderId}")
    public Result<OrderVO> getOrderDetail(@PathVariable Long orderId) {
        // 从当前用户获取企业ID
        Long enterpriseId = UserContext.getCurrentUserEnterpriseId();
        
        OrderVO orderDetail = demandOrderService.getOrderDetail(orderId, enterpriseId);
        return Result.success(orderDetail);
    }
    
    /**
     * 完成订单
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PutMapping("/{orderId}/finish")
    public Result<String> finishOrder(@PathVariable Long orderId) {
        // 从当前用户获取企业ID
        Long enterpriseId = UserContext.getCurrentUserEnterpriseId();
        
        demandOrderService.finishOrder(orderId, enterpriseId);
        return Result.success("");
    }
    
    /**
     * 搜索订单
     * @param queryDTO 搜索参数
     * @return 订单分页列表
     */
    @GetMapping("/search")
    public Result<IPage<OrderListVO>> searchOrders(OrderQueryDTO queryDTO) {
        // 从当前用户获取企业ID
        Long enterpriseId = UserContext.getCurrentUserEnterpriseId();
        queryDTO.setEnterpriseId(enterpriseId);
        
        IPage<OrderListVO> searchResult = demandOrderService.searchOrders(queryDTO);
        return Result.success(searchResult);
    }
}